//
// Created by xusun on 2022/1/28.
//

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
#include "iostream"

using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;

    TreeNode() : val(0), left(nullptr), right(nullptr) {}

    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
private:
    int count = 0;
    int k_tmp = 0;
    int ret_tmp = 0;

    void l2r(TreeNode *root) {
        if (root != NULL) {
            l2r(root->left);
            if (++count == k_tmp) ret_tmp = root->val;
            l2r(root->right);
        }
    }

public:
    int kthSmallest(TreeNode *root, int k) {
        k_tmp = k;
        l2r(root);
        return ret_tmp;
    }
};